<template>
  <el-dialog
    v-model="upOpen"
    title="上传下载文件"
    width="600px"
    :before-close="cancelHandler"
  >
    <el-row>
      <el-col :span="8">
        <el-form label-position="top">
          <el-form-item label="文件上传" class="uploadBox">
            <el-upload
              ref="uploads"
              v-loading="uploadLoading"
              action="#"
              class="upload-demo"
              multiple
              :limit="1"
              :http-request="uploadFile"
              :auto-upload="autoUpload"
              :on-exceed="handleExceed"
            >
              <el-button type="primary" plain>点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="16">
        <el-table
          v-loading="loading"
          :data="UploadingData"
          style="width: 100%;"
          max-height="250"
        >
          <el-table-column prop="operatorTime" label="日期"></el-table-column>
          <el-table-column prop="fileName" label="名称"></el-table-column>
          <el-table-column label="操作" fixed="right" width="100">
            <template #default="scope">
              <el-button
                type="primary"
                text
                size="small"
                @click="downloadRow(scope.row)"
              >
                下载
              </el-button>
              <el-button
                type="primary"
                text
                size="small"
                @click="delRow(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>;
        </el-table>
      </el-col>
    </el-row>
    <div style="text-align: right;margin-top: 10px;">
      <el-button type="info" @click="cancelHandler">取消</el-button>
      <el-button type="primary" :loading="saveUpload" @click="confirmHandler">确定</el-button>
    </div>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { aircabinetFile, deleteFile, selectFileList } from '@/api/expressManager/flySea'

const upOpen = ref(false)
const loading = ref(false)
const uploads = ref(null)
const ladingNo = ref(undefined)
const uploadLoading = ref(false)

const formData = ref(new FormData())
const autoUpload = ref(true)
const saveUpload = ref(false)
const UploadingData = ref([])

const initTable = () => {
  loading.value = true
  selectFileList({
    ladingNo: ladingNo.value,
  }).then(res => {
    if (res.code === 200) {
      UploadingData.value = res.data
    }
  }).finally(() => {
    loading.value = false
  })
}

const open = () => {
  upOpen.value = true
  initTable()
  resetFormData()
}
const downloadRow = (row: { [key: string]: any }) => {
  createDownload(unescape(row.file), row.fileName)
  console.log(row.file)
}
const createDownload = (url, filename) => {
  const a = document.createElement('a')
  a.download = filename
  a.href = url
  a.target = '_blank'
  a.click()
}
const delRow = async (row: { [key: string]: any }) => {
  ElMessageBox.confirm('确定删除, 是否继续?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    loading.value = true
    deleteFile(row.id).then(res => {
      if (res.code == 200) {
        ElMessage.success('删除文件成功！')
        initTable()
      } else {
        ElMessage.error('删除文件失败！')
      }
    }).finally(() => {
      loading.value = false
    })
  })
}
const confirmHandler = () => {
  const ladingNos = ladingNo.value
  if (formData.value.get('file')) {
    formData.value.append('ladingNo', ladingNos)
    saveUpload.value = true
    return aircabinetFile(formData.value)
    .then(res => {
      const { code } = res
      if (code === 200) {
        ElMessage.success('上传文件成功！') 
        resetFormData()
        initTable()
      }
    })
    .catch(error => {
      ElMessage.error('上传文件失败！')
      console.log(error)
    }).finally(() => {
      saveUpload.value = false
    })
  }
  cancelHandler()
}
const cancelHandler = () => {
  upOpen.value = false
  resetFormData()
}

const resetFormData = () => {
  formData.value.delete('file')
  nextTick(() => {
    uploads.value && uploads.value.clearFiles()
  })
}
const handleExceed = () => {
  if (formData.value.get('file')) return ElMessage.error('只能上传一个文件（上传多个文件可以使用.zip格式）')
}
const uploadFile = (file) => {
  formData.value.append('file', file.file)
}
defineExpose({
  ladingNo,
  open,
})
</script>